package com.dong.demo222.service.impl;


import com.dong.demo222.domin.SysRole;
import com.dong.demo222.domin.SysUser;
import com.dong.demo222.mapper.SysRoleMapper;
import com.dong.demo222.mapper.SysUserMapper;
import com.dong.demo222.model.AjaxResult;
import com.dong.demo222.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class PermissionServiceImpl implements IPermissionService
{
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysMenuServiceImpl sysMenuService;


    @Override
    public Set<String> getRolePermission(User user) {

        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if ("admin".equals(user.getUsername()))
        {
            roles.add("admin");
        }else{
//            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
            SysUser sysUser = userMapper.selectUserByUsername(user.getUsername());
            List<SysRole> perms = roleMapper.selectRolePermissionByUserId(sysUser.getUserId());
            Set<String> permsSet = new HashSet<>();
            for (SysRole perm : perms)
            {
                if (null!=perm)
                {
                    permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }





        }
        return roles;
    }

    @Override
    public Set<String> getMenuPermission(User user) {
        SysUser sysUser = userMapper.selectUserByUsername(user.getUsername());
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if ("admin".equals(user.getUsername()))
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = sysUser.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    Set<String> rolePerms = sysMenuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }
            else
            {
                perms.addAll(sysMenuService.selectMenuPermsByUserId(sysUser.getUserId()));
            }
        }
        return perms;
    }
}
